package com.gantang.lowcode.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gantang.lowcode.dto.Resource;
import com.gantang.lowcode.req.EmbedReq;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.*;

public class MetaBaseUtil {
    private static final ObjectMapper mapper = new ObjectMapper();

    public static String generateToken(EmbedReq embedReq, String embedSecretKey) {
        Map<String, Object> params = new HashMap<>();
//        params.put(":#supplier_id", embedReq.getParams().get("supplier_id"));
//        params.put("supplier_id", embedReq.getParams().get("supplier_id"));




        Map<String, Object> claims = new HashMap<>();
        claims.put("resource", embedReq.getResource());
        claims.put("params", Objects.isNull(embedReq.getParams()) ? new HashMap() : embedReq.getParams());
//        claims.put("params", params);

        return Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, embedSecretKey.getBytes())
                .compact();
    }

    public static List<Resource> extractResources(String json) {
        JsonNode root = null;
        try {
            root = mapper.readTree(json);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        List<Resource> resources = new ArrayList<>();

        if (root.isArray()) {
            for (JsonNode node : root) {
                int id = node.get("id").asInt();
                String name = node.get("name").asText();
                resources.add(new Resource(id, name));
            }
        }
        return resources;
    }
}
